﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FunnyArts.PrettyClient.Core.Logger
{
    public class FileLogger: ILogger
    {
        private readonly string _logFilePath;
        private readonly object _lock = new object();

        public FileLogger(string logFilePath)
        {
            _logFilePath = logFilePath;
        }

        public IDisposable BeginScope<TState>(TState state) => null;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }

            lock (_lock)
            {
                var filePath = Path.GetDirectoryName(_logFilePath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                if (!File.Exists(_logFilePath))
                {
                    using (var file=File.Create(_logFilePath))
                    {
                        file.Close();
                    };
                }
                File.AppendAllText(_logFilePath, formatter(state, exception) + Environment.NewLine);
            }
        }
    }
}
